import com.sun.source.tree.Tree;

public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     *
     * @param key
     */
    public boolean insert(int key) {
        TreeNode newNode = new TreeNode(key);

        TreeNode cur = root;
        if (root == null) {
            root = newNode;
            return true;
        }
        while (cur != null) {
            if (key > cur.key) {
                cur = cur.right;
            } else if (key < cur.key) {
                cur = cur.left;
            } else {
                return false;
            }
        }
        return true;
    }

    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur != null) {
            if (key < cur.key) {
                cur = cur.left;
            } else if (key > cur.key) {
                cur = cur.right;
            } else {
                return cur;
            }
        }
        return null;
    }

    //删除key的值
    public boolean remove(int key) {
        TreeNode cur = root;
        //找到删除的结点的父亲结点
        TreeNode parent = null;
        while (cur != null) {
            if (key < cur.key) {
                parent = cur;
                cur = cur.left;
            } else if (key > cur.key) {
                parent = cur;
                cur = cur.right;
            } else {
                removeNode(parent, cur);
            }
        }
        return false;
    }

    //
    private void removeNode(TreeNode parent, TreeNode cur) {
        if (cur.left == null) {
            if (cur == root) {
                root = cur.right;
            } else {
                if (cur == parent.left) {
                    parent.left = cur.right;
                } else if (cur == parent.right) {
                    parent.right = cur.right;
                }
            }
        } else if (cur.right == null) {
            if (cur == root) {
                root = cur.left;
            } else {
                if (cur == parent.left) {
                    parent.left = cur.left;
                } else if (cur == parent.right) {
                    parent.right = cur.left;
                }
            }
        } else {
            //cur左右都不为空

        }
    }
}